package gate.controller;

import base.correspond.CorrespondBean;
import base.correspond.ForwardUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;

@Controller
@ResponseBody
public class LoginRegisterController {
    @Autowired
    RestTemplate restTemplate;
    private static final String REST_URL_PREFIX_AUTH = "http://AUTH-SERVICE/api/auth";

    @PostMapping("/toLogin")
    public CorrespondBean toLogin (HttpServletRequest request) {
        CorrespondBean correspondBean = restTemplate.postForObject(REST_URL_PREFIX_AUTH + "/toLogin", ForwardUtil.getKeyValueMapForParams(request), CorrespondBean.class);
        if (correspondBean.getCode() == CorrespondBean.FAIL) {
            return CorrespondBean.getFailBean(correspondBean.getMessage());
        } else {
            return CorrespondBean.getSuccessBean(correspondBean.getMessage(), correspondBean.getData());
        }
    }

    @PostMapping("/toRegister")
    public CorrespondBean toRegister (HttpServletRequest request) {
        CorrespondBean correspondBean = restTemplate.postForObject(REST_URL_PREFIX_AUTH + "/toRegister", ForwardUtil.getKeyValueMapForParams(request), CorrespondBean.class);
        if (correspondBean.getCode() == CorrespondBean.SUCCESS) {
            return CorrespondBean.getSuccessBean("message", correspondBean.getMessage());
        } else {
            return CorrespondBean.getFailBean("register", correspondBean.getMessage());
        }
    }

    @RequestMapping("/toActive/{userCode}")
    public CorrespondBean toActive(@PathVariable("userCode") String userCode, Model model) {
        CorrespondBean correspondBean = restTemplate.getForObject(REST_URL_PREFIX_AUTH + "/toActive/" + userCode, CorrespondBean.class);
        return CorrespondBean.getSuccessBean(correspondBean.getMessage());
    }
}
